package com.heima.admin.gateway.filter;

import com.aliyuncs.utils.StringUtils;
import com.heima.common.dtos.Payload;
import com.heima.common.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Component
public class AuthFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 判断是否是登录请求
        String uri = request.getURI().getPath();
        if(isLogin(uri)){
            // 是，直接放行
            return chain.filter(exchange);
        }
        // 否，判断是否有token
        String token = request.getHeaders().getFirst("token");
        if(StringUtils.isEmpty(token)){
            // 401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 是，校验token是否有效
        try{
            Payload payload = JwtUtils.getInfoFromToken(token);
            Integer userId = payload.getUserId();
            if(userId != null && userId > 0){
                // 有效
                request.mutate().header("userId", ""+userId);
                return chain.filter(exchange);
            }else{
                // 401
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
        }catch(Exception e){
            log.error("token校验异常, uri:{}, token:{},详情:{}", uri, token, ExceptionUtils.getStackTrace(e));
            // 401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
    }

    private boolean isLogin(String uri) {
        if(uri.indexOf("/login/in") >= 0){
            return true;
        }
        return false;
    }
}
